﻿module Sustainalytics.Accounts.Admin {
    
    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;

    export class IpAuthenticationDetailsController {

        public accountInfo: AccountIpAuthenticationDto;
        public ipError:boolean;
        private $routeParams:any;
        constructor(
            private $scope: ng.IScope,
            private $location:ng.ILocationService,
            private ipAuthServices: IpAuthenticationService,    
            private routingService: Routing.IRoutingService,
            private accService: AccountsService
            
            ) {
            var ctx = this;
            ctx.ipError = false;
            ctx.$routeParams = routingService.getRouteParams();
            //ctx.ipAuthServices.getAccountIpData(ctx.$routeParams.accountId).then(a => {
            //    ctx.accountInfo = a;
            //});
            ctx.initStuff();
        }

        private initStuff() {
            var ctx = this;
            ctx.ipAuthServices.getAccountIpData(ctx.$routeParams.accountId).then(a => {
                ctx.accountInfo = a;
                if (!ctx.accountInfo) {
                    ctx.accService.accountGet(ctx.$routeParams.accountId).then(c => {
                        var newObj = new AccountIpAuthenticationDto(ctx.$routeParams.accountId, c.name, []);
                        ctx.accountInfo = newObj;
                    });
                }
            });
        }

        public addRecord() {
            var ctx = this;
            if (!ctx.accountInfo) ctx.accountInfo = new AccountIpAuthenticationDto(ctx.$routeParams.accountId,"", []);
            ctx.accountInfo.ipDatas.push(new IpData("", ""));
        }

        public remove(index: number) {
            var ctx = this;
            if (!ctx.accountInfo) return;
            ctx.accountInfo.ipDatas.splice(index, 1);
        }

        public saveData() {
            var ctx = this;

            if (ctx.ipError) return;
            ctx.ipAuthServices.putAccountIpData(ctx.accountInfo).then(succes => {
                console.log(succes);
            }, error => {
                console.log(error);
            });

        }

        public cancelModification() {
            var ctx = this;
            ctx.initStuff();
        }
    }


    var mod = angular.module(accountAdminModuleName);
    mod.controller('IpAuthenticationDetailsController', ['$scope', '$location', 'IpAuthenticationService', 'RoutingService','AccountsService', IpAuthenticationDetailsController]);
} 